import { createRouter, createWebHistory } from 'vue-router'
import Login from '../components/Login.vue'
import Register from '../components/Register.vue'
import Notice from '../components/Notice.vue'
import Details from '../components/Detail.vue'
import Group from '../components/Group.vue'
import AddF from '../components/AddF.vue'
import Home from '../components/Home.vue'
import { getValueBykey } from '../indexDB/dbKV'
import { tr } from 'element-plus/es/locales.mjs'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/login/',
    name: 'Login',
    component: Login
  },
  {
    path: '/register/',
    name: 'Register',
    component: Register
  },
  {
    path: '/notice/',
    name: 'Notice',
    component: Notice,
    meta: { requiresAuth: true }
  },
  {
    path: '/details/',
    name: 'Details',
    component: Details,
    meta: { requiresAuth: true }
  },
  {
    path: '/group/',
    name: 'Group',
    component: Group,
    meta: { requiresAuth: true }
  },
  {
    path: '/addF/',
    name: 'AddF',
    component: AddF,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加全局路由守卫
router.beforeEach(async (to, from, next) => {
  // 检查用户是否已登录
  const userInfo = await getValueBykey("userInfo")
  const token = await getValueBykey("token")
  
  // 如果需要登录的页面但没有登录，重定向到登录页
  if (to.meta.requiresAuth && (!userInfo || !token)) {
    next('/login')
  } else {
    next()
  }
})

export default router